;(function($){
    "use strict";

    jQuery.toast = function(content,type) {
        var toastType = '';
        var typeClass = 'ui_toast';
        var typeClass2 = '';
        if(type == 'success') {
            toastType = '<i class="weui-icon-success-no-circle weui-icon_toast"></i>';
            typeClass = 'weui-toast';
            typeClass2 = 'weui-toast__content';
        }
        else if(type == 'loading') {
            toastType = '<i class="weui-loading weui-icon_toast"></i>';
            typeClass = 'weui-toast';
            typeClass2 = 'weui-toast__content';
        }
        var string = '<div id="toast">' +
            '<div class="weui-mask_transparent"></div>' +
            '<div class="'+typeClass+'">' +
            toastType +
            '<p class="'+typeClass2+'">'+content+'</p>' +
            '</div>' +
            '</div>';
        $('body').append(string);
        if(type != 'loading') {
            setTimeout(function () {
                $('#toast').remove();
            }, 1500);
        }
    };

    jQuery.popup = function(title,content,btn,type) {

        if(type == "confirm" || !type) {
            var btns = btn.split(',');
            var btn1 = btns[0] || "确认";
            var btn2 = btns[1] || "取消";
            var str = '<div class="mask" id="popup-dialog">' +
                        '<div class="dialog-content">' +
                        '<div class="title">'+title+'</div>' +
                        '<div class="content">'+content+'</div>' +
                        '<div class="wrapBtns">' +
                        '<span class="submit">'+btn1+'</span>' +
                        '<span class="cancel">'+btn2+'</span>' +
                        '</div>' +
                        '</div>' +
                        '</div>';
        }
        $('body').append(str);
        $('#popup-dialog .cancel').click(function(e) {
            $('body').find('#popup-dialog').remove();
        });
    };

    /**
     * zepto插件：向左滑动删除动效
     * 使用方法：$('.itemWipe').touchWipe({itemDelete: '.item-delete'});
     * 参数：itemDelete  删除按钮的样式名
     */
    $.fn.touchWipe = function(option) {
        var defaults = {
            itemDelete: '.item-delete' //删除元素
        };
        var opts = $.extend({}, defaults, option); //配置选项

        var delWidth = $(opts.itemDelete).width();

        var initX; //触摸位置
        var moveX; //滑动时的位置
        var X = 0; //移动距离
        var objX = 0; //目标对象位置
        window.addEventListener('touchstart', function(event) {

            var obj = event.target.parentNode.parentNode;
            if (obj.className.indexOf("list-li") >=0) {
                event.preventDefault();
                initX = event.targetTouches[0].pageX;
                objX = (obj.style.WebkitTransform.replace(/translateX\(/g, "").replace(/px\)/g, "")) * 1;
                console.log(objX);
            }
            if (objX == 0) {
                window.addEventListener('touchmove', function(event) {

                    var obj = event.target.parentNode.parentNode;
                    if (obj.className.indexOf("list-li") >=0) {
                        event.preventDefault();
                        moveX = event.targetTouches[0].pageX;
                        X = moveX - initX;
                        if (X >= 0) {
                            obj.style.WebkitTransform = "translateX(" + 0 + "px)";
                        } else if (X < 0) {
                            var l = Math.abs(X);
                            obj.style.WebkitTransform = "translateX(" + -l + "px)";
                            if (l > delWidth) {
                                l = delWidth;
                                obj.style.WebkitTransform = "translateX(" + -l + "px)";
                            }
                        }
                    }
                });
            } else if (objX < 0) {
                window.addEventListener('touchmove', function(event) {

                    var obj = event.target.parentNode.parentNode;
                    if (obj.className.indexOf("list-li") >=0) {
                        event.preventDefault();
                        moveX = event.targetTouches[0].pageX;
                        X = moveX - initX;
                        if (X >= 0) {
                            var r = -delWidth + Math.abs(X);
                            obj.style.WebkitTransform = "translateX(" + r + "px)";
                            if (r > 0) {
                                r = 0;
                                obj.style.WebkitTransform = "translateX(" + r + "px)";
                            }
                        } else { //向左滑动
                            obj.style.WebkitTransform = "translateX(" + -delWidth + "px)";
                        }
                    }
                });
            }

        })
        $(this).on('touchend', function(event) {
            event.preventDefault();
            var obj = this;
            objX = (obj.style.WebkitTransform.replace(/translateX\(/g, "").replace(/px\)/g, "")) * 1;
            if (objX > -delWidth / 2) {
                obj.style.transition = "all 0.2s";
                obj.style.WebkitTransform = "translateX(" + 0 + "px)";
                obj.style.transition = "all 0";
                objX = 0;
            } else {
                obj.style.transition = "all 0.2s";
                obj.style.WebkitTransform = "translateX(" + -delWidth + "px)";
                obj.style.transition = "all 0";
                objX = -delWidth;
            }
        })

        //链式返回
        return this;
    };

    /**
     * ajax封装
     * url 发送请求的地址
     * data 发送到服务器的数据，数组存储，如：{"date": new Date().getTime(), "state": 1}
     * async 默认值: true。默认设置下，所有请求均为异步请求。如果需要发送同步请求，请将此选项设置为 false。
     *       注意，同步请求将锁住浏览器，用户其它操作必须等待请求完成才可以执行。
     * type 请求方式("POST" 或 "GET")， 默认为 "GET"
     * dataType 预期服务器返回的数据类型，常用的如：xml、html、json、text
     * successfn 成功回调函数
     * errorfn 失败回调函数
     */
    jQuery.axse=function(url, data, async, type, dataType, successfn, errorfn) {
        async = (async==null || async=="" || typeof(async)=="undefined")? "true" : async;
        type = (type==null || type=="" || typeof(type)=="undefined")? "post" : type;
        dataType = (dataType==null || dataType=="" || typeof(dataType)=="undefined")? "json" : dataType;
        data = (data==null || data=="" || typeof(data)=="undefined")? {"date": new Date().getTime()} : data;
        $.ajax({
            type: type,
            async: async,
            data: data,
            url: url,
            dataType: dataType,
            success: function(d){
                successfn(d);
            },
            error: function(e){
                errorfn(e);
            }
        });
    };

    /*降序排序、升序排序*/
    jQuery.sortNum = function(array,type) {
        function compare1() { //降序
            if(arguments[0]<arguments[1]) {
                return 1;
            } else if(arguments[0]>arguments[1]) {
                return -1;
            } else {
                return 0;
            }
        };
        function compare2() { //升序
            if(arguments[0]<arguments[1]) {
                return -1;
            } else if(arguments[0]>arguments[1]) {
                return 1;
            } else {
                return 0;
            }
        };
        if(!type || type == "ascending") { //默认升序
            return array.sort(compare2);
        }
        if(type == "descending") {
            return array.sort(compare1);
        }

    };

    /*查询url参数*/
    jQuery.getUrlParameter = function(url,name) {
        var targetUrl = url.search || location.search;
        var qs = targetUrl.length > 0 ? targetUrl.substring(1) : "";
        var args = {};
        var items = qs.length ? qs.split('&') : [];
        for(var i=0; i<items.length; i++){
            var item = items.split('=');
            args[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
        }
        if(name) {
            return args[name];
        } else {
            return args;
        }
    };

    /*获取两个数之间的随机数*/
    jQuery.randomNum = function(min,max) { //包含 min, max两个数值
        var numSize = max - min +1;
        return Math.floor(Math.random()*numSize + min);
    };

    /*获取任意位随机字符串*/
    jQuery.randomString = function(num) {
        var str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.split("");
        var randomStr = "";
        for(var i=0; i<num; i++) {
            randomStr += str[Math.floor(Math.random()*62)];
        }
        return randomStr;
    }

    $('.nav-title .backBtn').click(function() {
        history.go(-1);
    });
    $('.nav-title .backBtn3').click(function() {
        history.go(-1);
    });
    $('.nav-title .searchIpt').focus(function(e) {
        var target = $(e.currentTarget);
        var parent = target.closest('.nav-title');
        parent.find('.placeholder').addClass('hide');
    });
    $('.nav-title .searchIpt').blur(function(e) {
        var target = $(e.currentTarget);
        var parent = target.closest('.nav-title');
        if(target.val() == '') {
            parent.find('.placeholder').removeClass('hide');
        }
    });
    $('.xn-date-filter .selectBox').click(function(e) {
        var target = $(e.currentTarget);
        if(target.is('.down')) {
            target.removeClass('down').addClass('up');
            target.find('.dropList').removeClass('hide');
        }
        else if(target.is('.up')) {
            target.removeClass('up').addClass('down');
            target.find('.dropList').addClass('hide');
        }
    });
    $('.xn-date-filter .selectBox .dropList .item').click(function(e) {
        var target = $(e.currentTarget);
        var parent = target.closest('.selectBox');
        parent.find('.iptBox').text(target.text());
    });


    $('.xn-dropList').click(function(e) {
        var target = $(e.currentTarget);
        var child = target.find('.iptBox');
        if(child.is('.down')) {
            child.removeClass('down').addClass('up');
            target.find('.dropList').removeClass('hide');
        }
        else if(child.is('.up')) {
            child.removeClass('up').addClass('down');
            target.find('.dropList').addClass('hide');
        }
    });
    $('.xn-dropList .dropList .item').click(function(e) {
        var target = $(e.currentTarget);
        var parent = target.closest('.xn-dropList');
        parent.find('.iptBox').text(target.text());
    });

    $('.xn-toggleList .xn-dropTitle').click(function(e) {
        var target = $(e.currentTarget);
        var child = target.find('.iptBox');
        var parent = target.closest('.xn-toggleList');
        if(child.is('.down')) {
            child.removeClass('down').addClass('up');
            parent.find('.contentBox').removeClass('hide');
        }
        else if(child.is('.up')) {
            child.removeClass('up').addClass('down');
            parent.find('.contentBox').addClass('hide');
        }
    });

})(jQuery);








